<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract 下载控制器
 * @author 张伟
 */
class Download extends CI_Controller {

    private $uploadDir = './resource/uploadfiles/temp/';

    //通过get请求导出页
    public function export_excel_index(){
        $sql = $this->input->get('sql');
        $render = $this->input->get('render');
        try {
            $renderFile = "./application/libraries/export/ExportExcel/{$render}.php";
            if (!file_exists($renderFile)) {
                throw new \Exception("渲染文件不存在");
            }
            include_once $renderFile;
            $export = new $render();
            echo $export->getTplIndex($export->decode($sql));
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }
    
    //excel导出过程,支持大数据导出(例如几十万条)
    public function export_excel(){
        $sql = $this->input->post('sql');
        $timestamp = $this->input->post('timestamp');
        $render = $this->input->post('render');
        
        header('Content-Type:application/json; charset=utf-8');
        try {
            $renderFile = "./application/libraries/export/ExportExcel/{$render}.php";
            if (!file_exists($renderFile)) {
                throw new \Exception("渲染文件不存在");
            }
            include_once $renderFile;
            $export = new $render();
            $info = $export->export($sql, $timestamp);
            echo json_encode(array(
                    'code' => 1,
                    'message' => 'success',
                    'data' => $info
                ), JSON_UNESCAPED_UNICODE);
        } catch (\Exception $e) {
            echo json_encode(array(
                    'code' => 0,
                    'message' => $e->getMessage(),
                    'data' => array()
                ), JSON_UNESCAPED_UNICODE);
        }
    }
    //文件下载
    public function down(){
        $file = $this->input->get('file');
        $md5 = $this->input->get('md5');
        $rename = $this->input->get('rename');
        $file = base64_decode(urldecode($file));
        if ($rename) {
            $fileName = base64_decode(str_replace(' ','+',urldecode($rename)));
        }else{
            $fileName = pathinfo($file, PATHINFO_FILENAME);
        }
        $filePath = realpath($file);
        $fileName = $fileName .'.'. pathinfo($filePath,PATHINFO_EXTENSION);
        

        if(!file_exists($filePath)){
            header('HTTP/1.1 404 Not Found');
            echo "Error: 404 Not Found.(server file path error)<!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding -->";
            exit;
        }
        //如果大于30M则通过链接下载
        if (filesize($filePath) > 1024*1024*30 && !strstr(PHP_OS, 'WIN')) {
            $link = $this->uploadDir.$fileName;
            symlink($filePath, $link);
            $url = trim($link, '.');
            header("Location: {$url}");
            exit;
        }
        if ($md5 && $md5 != md5(file_get_contents($filePath))) {
            header('HTTP/1.1 200 OK');
            header("Content-type: text/html; charset=utf-8"); 
            exit('文件已被修改,下载失败.');
        }

        
        
        $encoded_filename = urlencode($fileName);
        $encoded_filename = str_replace("+", "%20", $encoded_filename);

        header('HTTP/1.1 200 OK');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Content-type: application/octet-stream");
        header("Content-Length: ".filesize($filePath));
        header("Accept-Ranges: bytes");
        header("Accept-Length: ".filesize($filePath));

        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
        }
        // 输出文件内容
        readfile($filePath);
        exit;
    }

}
